﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.WebUI.Controllers
{
    public class HobbyXAjaxDropDownController : Controller
    {
        private readonly IRepo<Person> personRepo;
        private readonly IRepo<Hobby> hobbyRepo;

        public HobbyXAjaxDropDownController(IRepo<Person> personRepo, IRepo<Hobby> hobbyRepo)
        {
            this.personRepo = personRepo;
            this.hobbyRepo = hobbyRepo;
        }

        public ActionResult GetItems(int? key, int? parent)
        {
            var list = new List<SelectListItem> { new SelectListItem { Text = "not selected", Value = "" } };
            var source = parent.HasValue ?
                personRepo.Get(parent.Value).Hobbies 
                : hobbyRepo.GetAll();

            list.AddRange(
                source.Select(o => new SelectListItem
                                       {
                                           Text = o.Name,
                                           Value = o.Id.ToString(),
                                           Selected = o.Id == key
                                       }));
            return Json(list);
        }
    }
}